<template>
	<div class="tab" ref="tabRef">
		<div class="dflex h100">
			<div class="tab_content h100 margin_r_10 dflex crpr pos_r" :class="{ active: home.path == $route.path }">
				<div class="tab_name h100 dflex_vertical_c padding_lr_10 sele_none" @click="toPage(home)">
					{{ home.name }}
				</div>
			</div>
			<vuedraggable class="dflex h100" draggable=".tab_content" :options="{ animation: 200 }" v-model="tabDatas">
				<div class="tab_content h100 margin_r_10 dflex crpr pos_r" v-for="(item, i) in tabDatas"
					:class="{ active: item.path == $route.path }" :key="i">
					<div class="tab_name h100 dflex_vertical_c padding_lr_10 sele_none" @click="toPage(item)">
						{{ item.name }}
						<div class="tab_close_after" v-if="item.close"></div>
					</div>
					<div class="iconfont iconcuowuguanbiquxiao pos_a tab_close" v-if="item.close"
						@click.stop="closeTab(i)">
					</div>
				</div>
			</vuedraggable>
		</div>
		<el-dropdown class="tab_btn" trigger="click" @command="handleTab">
			<el-button size="mini" class="h100">
				标签选项
				<i class="el-icon-arrow-down margin_l_5"></i>
			</el-button>
			<el-dropdown-menu slot="dropdown" class="sele_none">
				<el-dropdown-item command="other">关闭其他</el-dropdown-item>
				<el-dropdown-item command="all">关闭所有</el-dropdown-item>
			</el-dropdown-menu>
		</el-dropdown>
	</div>
</template>

<script>
	import vuedraggable from 'vuedraggable';
	const __storage_key = 'wmzmall-tabs';
	export default {
		components: {
			vuedraggable
		},
		data() {
			return {
				tabDatas: [],
				home: {},
				menus: [],
				tagTotal: 12,
				prevRoute: {}
			};
		},
		watch: {
			$route(newValue, oldValue) {
				let __newValue = {
					path: newValue.path,
					fullPath: decodeURIComponent(newValue.fullPath),
					queryTab: decodeURIComponent(newValue.query.tab)
				}

				this.prevRoute = {
					path: newValue.path,
					fullPath: decodeURIComponent(newValue.fullPath)
				};

				// 添加当前路由 tab
				if (this.addTab(__newValue)) {
					uni.$emit('routeChange', __newValue);
				} else {
					this.notPermission();
				}
			},
			tabDatas(newValue, oldValue) {
				uni.setStorage({
					key: __storage_key,
					data: newValue
				});
			}
		},
		methods: {
			initTab() {
				this.menus = uni.getStorageSync('__menu') || [];
				this.home = uni.getStorageSync('__menu_first') || {};
				this.home.close = false;

				if (this.home.fullPath == '/pages/home') {
					this.home.fullPath = '/';
					this.home.path = '/';
					this.home.url = '/';
				}

				this.tabDatas = [];

				const tabs = uni.getStorageSync(__storage_key);
				if (tabs && tabs.length > 0) {
					this.tabDatas = tabs;
				}
			},
			closeTab(index) {
				const delItem = this.tabDatas.splice(index, 1)[0];

				// 判断删除是否为当前路径
				if (delItem.path === this.$route.path) {
					// 判断上一个路由地址是否存在于 tabDatas 中
					if (this.tabDatas.find(x => x.path == delItem.prevRoute.path)) {
						// 跳回上一个路由
						uni.redirectTo({
							url: delItem.prevRoute.fullPath
						});
					} else {
						// 跳回上一个或下一个
						const item = this.tabDatas[index] ? this.tabDatas[index] : this.tabDatas[index - 1];
						if (item) {
							uni.redirectTo({
								url: item.fullPath
							});
						} else {
							// 跳回首页
							uni.redirectTo({
								url: this.home.path
							});
						}
					}
				}

				for (let key in localStorage) {
					if (key.indexOf('__scroll' + delItem.path) != -1) {
						if (key != '__scroll/') {
							uni.removeStorageSync(key);
						}
					}
					if (key.indexOf('__tabs' + delItem.path) != -1) {
						uni.removeStorageSync(key);
					}
					if (key.indexOf('__search' + delItem.path) != -1) {
						uni.removeStorageSync(key);
					}
				}
			},
			addTab(route) {
				const curPath = route.path;

				if (curPath == '/') {
					uni.redirectTo({
						url: this.home.path
					});
					return true;
				}

				if (['/pages/login', '/pages/error/404', '/pages/bi/wmzmall_bi', '/preview-image'].includes(curPath)) {
					return true;
				}

				const isExist = this.tabDatas.some(item => {
					return item.path === curPath;
				});
				const menu = this.menus.find(x => x.url == route.path) || {
					name: route.queryTab
				};

				if (!isExist && route.fullPath != this.home.fullPath) {
					if (this.tabDatas.length >= this.tagTotal) {
						const delItem = this.tabDatas.splice(1, 1)[0];

						for (let key in localStorage) {
							if (key.indexOf('__scroll' + delItem.path) != -1) {
								if (key != '__scroll/') {
									uni.removeStorageSync(key);
								}
							}
							if (key.indexOf('__tabs' + delItem.path) != -1) {
								uni.removeStorageSync(key);
							}
							if (key.indexOf('__search' + delItem.path) != -1) {
								uni.removeStorageSync(key);
							}
						}
					}

					if (menu && menu.name) {
						this.tabDatas.push({
							name: menu.name,
							path: curPath,
							fullPath: route.fullPath,
							close: true,
							prevRoute: {
								path: this.prevRoute.path,
								fullPath: this.prevRoute.fullPath
							}
						});
						return true;
					}
				} else {
					// 修改当前 tab 的 prevRoute
					let curTab = this.tabDatas.find(x => x.path == curPath);
					if (curTab) {
						curTab.prevRoute = {
							path: this.prevRoute.path,
							fullPath: this.prevRoute.fullPath
						};
						curTab.name = menu.name;
					}
					return true;
				}

				return false;
			},
			handleTab(command) {
				command === 'other' ? this.closeOther() : this.closeAll();
			},
			closeAll() {
				this.tabDatas = [];
				uni.redirectTo({
					url: this.home.path
				});

				for (let key in localStorage) {
					if (key.indexOf('__scroll') != -1) {
						if (key != '__scroll/') {
							uni.removeStorageSync(key);
						}
					}
					if (key.indexOf('__tabs') != -1) {
						uni.removeStorageSync(key);
					}
					if (key.indexOf('__search') != -1) {
						uni.removeStorageSync(key);
					}
				}
			},
			closeOther() {
				const curItem = this.tabDatas.find(item => {
					return item.path === this.$route.path;
				});

				this.tabDatas = [];
				if (curItem.path !== this.home.path) this.tabDatas.push(curItem);

				for (let key in localStorage) {
					if (key.indexOf('__scroll') != -1) {
						if (key.indexOf(this.$route.path) === -1 && key != '__scroll/') {
							uni.removeStorageSync(key);
						}
					}
					if (key.indexOf('__tabs') != -1) {
						if (key.indexOf(this.$route.path) === -1) {
							uni.removeStorageSync(key);
						}
					}
					if (key.indexOf('__search') != -1) {
						if (key.indexOf(this.$route.path) === -1) {
							uni.removeStorageSync(key);
						}
					}
				}
			},
			notPermission() {
				this.$notify.error({
					title: '错误',
					message: '您没有权限！'
				});
				// 跳转到最后一个 tab
				uni.redirectTo({
					url: this.tabDatas[this.tabDatas.length - 1].path
				});
			},
			toPage(item) {
				if (item.fullPath != this.$route.fullPath) {
					uni.redirectTo({
						url: item.fullPath
					});
				}
			}
		},
		created() {
			this.initTab();

			let __route = {
				path: this.$route.path,
				fullPath: decodeURIComponent(this.$route.fullPath),
				queryTab: decodeURIComponent(this.$route.query.tab)
			}

			// 添加当前路由 tab
			if (this.addTab(__route)) {
				uni.$emit('routeChange', __route);
			} else {
				this.notPermission();
			}

			uni.$on('closeTab', () => {
				this.tabDatas.forEach((tag, index) => {
					if (tag.path == this.$route.path) {
						this.tabDatas.splice(index, 1);
						return false;
					}
				});

				for (let key in localStorage) {
					if (key.indexOf('__scroll' + this.$route.path) != -1) {
						if (key != '__scroll/') {
							uni.removeStorageSync(key);
						}
					}
					if (key.indexOf('__tabs' + this.$route.path) != -1) {
						uni.removeStorageSync(key);
					}
					if (key.indexOf('__search' + this.$route.path) != -1) {
						uni.removeStorageSync(key);
					}
				}
			});

			// 登录
			uni.$on('loginIn', () => {
				this.initTab();
			});
			// 退出
			uni.$on('loginOut', () => {
				this.tabDatas = [];
			});
		},
		mounted() {
			this.$nextTick(() => {
				uni.$on('fold', res => {
					if (res) {
						if (this.$refs.tabRef) this.$refs.tabRef.style.left =
							'calc(16px + var(--window-left))';
					} else {
						if (this.$refs.tabRef) this.$refs.tabRef.style.left =
							'calc(16px + var(--window-left))';
					}
				});
			});
		}
	};
</script>

<style>
	.tab {
		position: fixed;
		top: 76px;
		left: 196px;
		right: 16px;
		overflow: hidden;
		transition: all 0.35s;
		z-index: 10;
		height: 36px;
	}

	.tab_content {
		border-radius: 4px;
		font-size: 12px;
		background: #fff;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.tab_content:not(.active):hover {
		background: #e6e6e6;
	}

	.tab_content.active {
		color: #fff;
		background: #8a8a8a;
	}

	.tab_content.active .tab_name {
		color: #fff;
	}

	.tab_name {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		color: #666;
	}

	.tab_close {
		font-size: 12px;
		top: 50%;
		right: 6px;
		transform: translateY(-50%);
	}

	.tab_close_after {
		width: 12px;
	}

	.tab_close:hover {
		background-color: #fff;
		color: #8a8a8a;
		border-radius: 50%;
	}

	.tab .el-button {
		border: none;
	}

	.tab_btn {
		position: absolute;
		right: 0;
		top: 0;
		box-sizing: border-box;
		text-align: center;
		z-index: 10;
		height: 100%;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		border-radius: 4px;
		overflow: hidden;
	}

	.tab_btn>>>.el-button:hover,
	.tab_btn>>>.el-button:focus {
		color: #fff;
		background: #ff6a6c;
	}
</style>
